<template>
  <div id="mapView" class="map-view">
    <!-- 维修站点列表面板 -->
    <div class="maintenance-panel" v-if="showMaintenanceList">
      <el-card>
        <div class="maintenance-header">
          <h3>附近维修站点</h3>
          <el-button @click="showMaintenanceList = false" size="small" type="text">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <el-checkbox-group v-model="selectedMaintenanceIds" :key="refreshKey">
          <el-checkbox
            v-for="maintenance in nearbyMaintenances"
            :key="maintenance.attributes.FID"
            :label="maintenance.attributes.FID"
            @change="showMaintenanceInfo(maintenance)"
          >
            {{ maintenance.attributes.maintenanceName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-card>
    </div>

    <!-- 维修站点详情对话框 -->
    <el-dialog v-model="maintenanceInfoVisible" title="维修站点详情" width="500px">
      <el-descriptions :column="1" border v-if="currentMaintenance">
        <el-descriptions-item label="站点名称">
          {{ currentMaintenance.attributes.maintenanceName }}
        </el-descriptions-item>
        <el-descriptions-item label="站点地址">
          {{ currentMaintenance.attributes.maintenanceAddress }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="maintenanceInfoVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 路线详情卡片 -->
    <div class="route-card" v-if="showRouteDetails">
      <div class="route-header">
        <h3>导航路线</h3>
        <el-button
          class="close-btn"
          type="info"
          circle
          size="small"
          @click="showRouteDetails = false"
        >
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </div>

      <div class="route-summary">
        <div class="summary-item">
          <el-icon>
            <Position />
          </el-icon>
          <span>{{ (routeDistance / 1000).toFixed(2) }}km</span>
        </div>
        <div class="summary-item">
          <el-icon>
            <Timer />
          </el-icon>
          <span>约{{ Math.ceil(routeTime / 60) }}分钟</span>
        </div>
      </div>

      <el-collapse accordion>
        <el-collapse-item title="导航指引">
          <div class="instructions-list">
            <div
              v-for="(instruction, index) in routeInstructions"
              :key="index"
              class="instruction-item"
            >
              {{ instruction }}
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { Close, Position, Timer } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Query from '@arcgis/core/rest/support/Query.js'
import Graphic from '@arcgis/core/Graphic.js'
import Polyline from '@arcgis/core/geometry/Polyline.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import { getGaoDeRoute } from '../utils/gaodeAPI'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import sign from '@/assets/sign.png'
import maintenance from '@/assets/maintenance.png'
import { ElMessage } from 'element-plus'
import gcoord from 'gcoord'

const showMaintenanceList = ref(false)
let nearbyMaintenances: any = []
const selectedMaintenanceIds = ref<number[]>([])
const maintenanceInfoVisible = ref(false)
const currentMaintenance = ref<any>(null)
const routeGraphics: Graphic[] = []
const routeDistance = ref(0)
const routeTime = ref(0)
const routeInstructions = ref<string[]>([])
const showRouteDetails = ref(false)
const refreshKey = ref(0)
let currentSign: __esri.Point | null = null
let view: MapView | null = null
let maintenanceLayer: FeatureLayer | null = null
let signLayer: FeatureLayer | null = null

// 显示维修站点详情
const showMaintenanceInfo = async (maintenance: any) => {
  currentMaintenance.value = JSON.parse(
    JSON.stringify(maintenance, (key, value) => {
      // 过滤掉ArcGIS特殊属性或不可序列化的对象
      if (key === '__accessor__' || typeof value === 'function' || key.startsWith('_')) {
        return undefined
      }
      return value
    }),
  )
  maintenanceInfoVisible.value = true

  // 如果用户选择了显示导航路径，则计算并显示路径
  if (selectedMaintenanceIds.value.includes(maintenance.attributes.FID)) {
    await calculateRoute(maintenance)
  }
}

// 查询附近维修站点
const queryNearbyMaintenances = async (geometry: any) => {
  if (!maintenanceLayer) return

  const query = new Query({
    geometry: geometry,
    distance: 5,
    units: 'kilometers',
    outFields: ['*'],
    returnGeometry: true,
  })

  try {
    ElMessage.success('正在查询附近5公里内的维修站点')
    const results = await maintenanceLayer.queryFeatures(query)
    if (results.features.length === 0) {
      ElMessage.warning('没有查询到维修站点')
      nearbyMaintenances = []
      return
    } else {
      ElMessage.success('查询到维修站点' + results.features.length + '个')
    }
    nearbyMaintenances = results.features.map((feature) => {
      return {
        attributes: { ...feature.attributes },
        geometry: feature.geometry as __esri.Point,
      }
    })
    showMaintenanceList.value = true
    nextTick(() => {
      refreshKey.value++
    })
  } catch (error) {
    console.error('查询维修站点出错:', error)
  }
}

// 计算导航路线
const calculateRoute = async (maintenance: any) => {
  if (!view) return


  try {
    // 清除之前的路线
    clearRoute()
    console.log(maintenance)
    console.log(currentSign)
    // 将Web Mercator坐标转换为WGS84坐标
    const maintenanceWGS84 = gcoord.transform(
      [maintenance.geometry.x, maintenance.geometry.y],
      gcoord.EPSG3857,
      gcoord.WGS84,
    )

    // 调用高德路径规划API
    const routeResult = await getGaoDeRoute(
      `${currentSign!.longitude},${currentSign!.latitude}`,
      `${maintenanceWGS84[0]},${maintenanceWGS84[1]}`,
    )
    console.log(routeResult)

    // 绘制路线
    if (routeResult && routeResult.route && routeResult.route.paths[0]) {
      const path = routeResult.route.paths[0]

      // 将路径点转换为二维数组
      const pathPoints = path.steps.flatMap((step) => {
        return step.polyline.split(';').map((point) => {
          const [lng, lat] = point.split(',').map(Number)
          return [lng, lat]
        })
      })

      // 创建路线图形
      const routeLine = new Graphic({
        geometry: new Polyline({
          paths: [pathPoints],
        }),
        symbol: new SimpleLineSymbol({
          color: [0, 122, 194, 0.8],
          width: 4,
        }),
      })

      view.graphics.add(routeLine)
      routeGraphics.push(routeLine)

      // 提取路线指引信息
      routeInstructions.value = path.steps.map((step) => step.instruction)

      // 设置路线距离和时间
      routeDistance.value = Number(path.distance)
      routeTime.value = Number(path.duration)

      // 显示路线详情
      showRouteDetails.value = true
      ElMessage.success('路线规划成功')
    } else {
      ElMessage.error('无法获取路线信息')
    }
  } catch (error) {
    console.error('路线规划失败', error)
    ElMessage.error('路线规划失败')
  }
}

// 清除路线
const clearRoute = () => {
  if (!view) return

  // 清除路线图形
  routeGraphics.forEach((graphic) => {
    view?.graphics.remove(graphic)
  })
  routeGraphics.length = 0

  // 重置路线信息
  routeInstructions.value = []
  routeDistance.value = 0
  routeTime.value = 0
  showRouteDetails.value = false
}

// 初始化地图
onMounted(() => {
  // 创建维修站点图层
  maintenanceLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/maintenance/FeatureServer/0',
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: new PictureMarkerSymbol({
        url: maintenance,
        width: 24,
        height: 24,
      }),
    },
  })
  // 创建标志牌图层
  signLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/2',
    title: '标志牌',
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: new PictureMarkerSymbol({
        url: sign,
        width: 24,
        height: 24,
      }),
    },
  })

  // 创建地图
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [maintenanceLayer, signLayer],
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    center: [116.7461293, 36.5598627],
    zoom: 12,
  })

  // 监听标志牌点击事件
  view.on('click', async (event) => {
    clearRoute()
    currentSign = event.mapPoint.clone()
    if (!signLayer || !maintenanceLayer) return

    const query = new Query({
      geometry: event.mapPoint,
      distance: 500,
      units: 'kilometers',
      outFields: ['*'],
      returnGeometry: true,
      where: '1=1', // 查询所有要素
    })

      const results = await signLayer.queryFeatures(query)
      if (results.features.length > 0) {
        queryNearbyMaintenances(event.mapPoint)
      }
  })
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.maintenance-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1;
  width: 300px;
}

.maintenance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.select-point-tip {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2;
  width: 300px;
}

.route-card {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 1;
  width: 300px;
  background: white;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.route-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item span {
  margin-left: 5px;
}

.instructions-list {
  max-height: 300px;
  overflow-y: auto;
}

.instruction-item {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}
</style>
